package com.banciyuan.bcywebview.biz.main.discover.topwork;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.IllustApi;
import com.banciyuan.bcywebview.base.factory.CardFactory;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Card;


public class TopWorkFragment extends BaseLazyContainerFragment {

    protected PullToRefreashRecycleView mPullToRefreshBase;
    private RecyclerView mRecyclerView;
    protected ProgressbarHelper mProgressbarHelper;
    private List<Card> mCardList = new ArrayList<>();
    private TopWorkAdapter adapter;
    private String mRankType;
    private int mType;
    private int page = 1;
    private boolean loading = false;
    private boolean isEnd = false;
    private String url;
    private String date;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.top_work_layout, container, false);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    protected void initArgs() {
        Bundle arguments = getArguments();
        mType = arguments.getInt(gotoUtil.INTENT_VALUE_ONE);
        mRankType = arguments.getString(gotoUtil.INTENT_VALUE_TWO);
        date = arguments.getString(gotoUtil.INTENT_VALUE_THREE);
        if (mType == TopWorkActivity.ILLUST_TYPE) {
            url = HttpUtils.BASE_URL + IllustApi.getIllustTopList();
        } else if (mType == TopWorkActivity.COS_TYPE) {
            url = HttpUtils.BASE_URL + CoserApi.getCoserTopList();
        }
    }

    @Override
    public void fetchData() {
        loading = false;
        isEnd = false;
        page = 1;
        initData();
    }


    @Override
    protected void initProgressbar(View rootview) {
        View mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!loading) {
                    loading = true;
                    mProgressbarHelper.onLoading();
                    isEnd = false;
                    page = 1;
                    initData();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        mPullToRefreshBase = (PullToRefreashRecycleView) rootview.findViewById(R.id.recleview);
        mRecyclerView = mPullToRefreshBase.getRefreshableView();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 0) {
                    return 2;
                } else if (position == mCardList.size() + 1) {
                    return 2;
                } else {
                    return 1;
                }
            }
        });
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view);
                if (position > 0 && position < mCardList.size() + 1) {
                    if ((position - 1) % 2 == 0) {
                        outRect.left = UIUtils.dip2px(12, getActivity());
                        outRect.right = UIUtils.dip2px(4, getActivity());
                    } else {
                        outRect.left = UIUtils.dip2px(4, getActivity());
                        outRect.right = UIUtils.dip2px(12, getActivity());
                    }
                }
            }

            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                c.drawColor(Color.WHITE);
            }
        });
        mRecyclerView.setLayoutManager(gridLayoutManager);
    }

    @Override
    protected void initAction() {
        mPullToRefreshBase.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                loading = false;
                isEnd = false;
                page = 1;
                initData();
            }
        });
        mRecyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!loading && !isEnd) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
    }

    @Override
    protected void initData() {
        loading = true;
        List<BcyPair> paramsList = new ArrayList<>();
        if (!TextUtils.isEmpty(mRankType)) {
            paramsList.add(new BcyPair(HttpUtils.TYPE, mRankType));
        }
        if (!TextUtils.isEmpty(date)) {
            paramsList.add(new BcyPair("date", date));
        }
        paramsList.add(new BcyPair(HttpUtils.PAGE, page + ""));
        Map<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray reData = jsonObject.getJSONArray(HttpUtils.UPLOAD_DATA);
                        List<Card> tempCardList = CardFactory.createCard(reData);
                        processData(tempCardList);
                        onSuccess();
                        BaseObserver.getInstance().notifyWatchers(BaseObserver.RANK_REFREASH);
                    }
                } catch (Exception e) {
                    onError();
                    BaseObserver.getInstance().notifyWatchers(BaseObserver.RANK_REFREASH);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onError();
                BaseObserver.getInstance().notifyWatchers(BaseObserver.RANK_REFREASH);
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSuccess, url, getActivity(), map);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSuccess, errorProxy);
        VolleyQueue.getRquest(getActivity()).add(getUserdataRequest);
    }

    private void onSuccess() {
        mProgressbarHelper.onSuccess();
        mPullToRefreshBase.onRefreshComplete();
        loading = false;
    }

    private void onError() {
        loading = false;
        mProgressbarHelper.onFailed();
        mPullToRefreshBase.onRefreshComplete();
    }

    private void processData(List<Card> tempCardList) {
        if (tempCardList.isEmpty()) {
            isEnd = true;
        }
        if (page == 1) {
            mCardList.clear();
        }
        int index = mCardList.size();
        mCardList.addAll(tempCardList);
        if (null == adapter) {
            adapter = new TopWorkAdapter(getActivity(), mCardList, mType);
            mRecyclerView.setAdapter(adapter);
        } else {
            if (page == 1) {
                adapter.notifyDataSetChanged();
            } else {
                adapter.notifyItemRangeInserted(index + 1, tempCardList.size());
            }
        }
    }

    @Override
    public void selfUpdateData() {
        if (isVisibleToUser) {
            mRecyclerView.smoothScrollToPosition(0);
            mPullToRefreshBase.setRefreshing();
        }
    }

    public void resetUi() {
        mProgressbarHelper.onLoading();
    }

    public void setDate(String date) {
        this.date = date;
    }
}
